package leetcode.hot100;

import java.util.*;

public class number438 {
    public static void main(String[] args) {
        String s = "abab";
        String p = "ab";
        List<Integer> anagrams = findAnagrams(s, p);
        anagrams.forEach(System.out::println);
    }
    public static List<Integer> findAnagrams(String s, String p) {
        List<Integer>reList=new ArrayList<>();

        int l=0,right=0;
        while (right<s.length()){
            //System.out.print(p.contains(s.charAt(right) + "")+" : ");
            //System.out.println(s.substring(l, right));
            if(p.contains(s.charAt(right) + "")){
                if(right+1-l==p.length()){
                    String substring = s.substring(l, right+1);
                    if(isAnagrams(substring,p)){
                        reList.add(l);
                    }
                    l++;
                    right++;
                }else{
                    right++;
                }
            }else {
                right++;
                l=right;
            }
        }

        return reList;
    }
    public static boolean isAnagrams(String s,String p){
        int al=s.length();
        int pl=p.length();
        if(al!=pl){
            return false;
        }
        char[] sa = s.toCharArray();
        char[] pa = p.toCharArray();
        Arrays.sort(sa);
        Arrays.sort(pa);
        for (int i=0;i<al;i++){
            if(sa[i]!=pa[i]){
                return false;
            }
        }
        return true;
    }
}
